package com.TTadsSdk;

import android.app.Dialog;
import android.util.Log;

import androidx.annotation.Nullable;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdManager;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTFullScreenVideoAd;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.bytedance.sdk.openadsdk.TTDrawFeedAd;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;
import com.magiccube.z7fire.MainActivity;

public class TTadsSdkModule extends ReactContextBaseJavaModule {
    public static final String REACT_CLASS = "TTAdFullScreenVideo";
    public static final String EVENT_AD_SHOWED = "fullScreenVideoAdShowed";
    public static final String EVENT_AD_VIDEO_BAR_CLICK = "fullScreenVideoAdClick";
    public static final String EVENT_AD_VIDEO_CLOSE = "fullScreenVideoAdClose";
    public static final String EVENT_AD_VIDEO_COMPLETE = "fullScreenVideoComplete";
    public static final String EVENT_AD_SKIPPED_VIDEO = "fullScreenVideoSkipped";
    public static final String EVENT_AD_FAILED_TO_LOAD = "fullScreenVideoAdFailedToLoad";

    private TTFullScreenVideoAd mttFullVideoAd;
    private TTRewardVideoAd mttRewardVideoAd;
    private static Dialog mSplashDialog;

    public TTadsSdkModule(@Nonnull ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Nonnull
    @Override
    public String getName() {
        return "TTadsSdk";
    }

    @ReactMethod
    public void showFullScreenVideoAd(String codeId) {
        try {
            initFullScreenVideoAd(codeId);
        } catch (Exception e) {
            Log.e("error...initFullScreenVideoAd", e.getMessage());
        }
    }

    @ReactMethod
    public void showRewardVideoAd(String codeId) {
        try {
            initTTRewardVideoAd(codeId);
        } catch (Exception e) {
            Log.e("error...initTTRewardVideoAd", e.getMessage());
        }
    }

    @ReactMethod
    public void showTTDrawFeedAd(String codeId) {
        try {
            initTTDrawFeedAd(codeId);
        } catch (Exception e) {
            Log.e("error...initTTDrawFeedAd", e.getMessage());
        }
    }


    // 向RN发送事件
    private void sendEvent(String eventName, @Nullable WritableMap params) {
        getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, params);
    }

    // 加载全屏广告
    // @ReactMethod
    private void initFullScreenVideoAd(String codeId) {
        //step1:初始化sdk
        TTAdManager ttAdManager = TTAdManagerHolder.get();
        //step2:(可选，强烈建议在合适的时机调用):申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
        TTAdManagerHolder.get().requestPermissionIfNecessary((MainActivity) getCurrentActivity());
        //step3:创建TTAdNative对象,用于调用广告请求接口
        TTAdNative mTTAdNative = ttAdManager.createAdNative((MainActivity) getCurrentActivity());
        //step4:创建广告请求参数AdSlot,具体参数含义参考文档
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(codeId)
                .setSupportDeepLink(true)
                .setImageAcceptedSize(1080, 1920)
                .setOrientation(TTAdConstant.VERTICAL)//必填参数，期望视频的播放方向：TTAdConstant.HORIZONTAL 或 TTAdConstant.VERTICAL
                .build();
        //step5:请求广告
        mTTAdNative.loadFullScreenVideoAd(adSlot, new TTAdNative.FullScreenVideoAdListener() {
            @Override
            public void onError(int code, String message) {
//                TToast.show(getCurrentActivity(), message + "message");
                WritableMap error = Arguments.createMap();
                error.putInt("code", code);
                error.putString("message", message);
                sendEvent(EVENT_AD_FAILED_TO_LOAD, error);
            }

            @Override
            public void onFullScreenVideoAdLoad(TTFullScreenVideoAd ad) {
                mttFullVideoAd = ad;
                mttFullVideoAd.setFullScreenVideoAdInteractionListener(new TTFullScreenVideoAd.FullScreenVideoAdInteractionListener() {

                    @Override
                    public void onAdShow() {
//                        TToast.show(getCurrentActivity(), "FullVideoAd show1");
                        sendEvent(EVENT_AD_SHOWED, null);
                    }

                    @Override
                    public void onAdVideoBarClick() {
//                        TToast.show(getCurrentActivity(), "FullVideoAd bar click");
                        sendEvent(EVENT_AD_VIDEO_BAR_CLICK, null);

                    }

                    @Override
                    public void onAdClose() {
//                        TToast.show(getCurrentActivity(), "FullVideoAd close");
                        sendEvent(EVENT_AD_VIDEO_CLOSE, null);

                    }

                    @Override
                    public void onVideoComplete() {
//                        TToast.show(getCurrentActivity(), "FullVideoAd complete");
                        sendEvent(EVENT_AD_VIDEO_COMPLETE, null);

                    }

                    @Override
                    public void onSkippedVideo() {
//                        TToast.show(getCurrentActivity(), "FullVideoAd skipped");
                        sendEvent(EVENT_AD_SKIPPED_VIDEO, null);
                    }

                });

                getCurrentActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mttFullVideoAd != null) {
                            mttFullVideoAd.showFullScreenVideoAd(getCurrentActivity(), TTAdConstant.RitScenes.GAME_GIFT_BONUS, null);
                        }
                    }
                });
            }

            @Override
            public void onFullScreenVideoCached() {
//                TToast.show(getCurrentActivity(), "FullVideoAd video cached");
            }
        });
    }





    // 激励视频失败
    // @ReactMethod 
    private void initTTRewardVideoAd(String codeId) {
        //step1:初始化sdk
        TTAdManager ttAdManager = TTAdManagerHolder.get();
        //step2:(可选，强烈建议在合适的时机调用):申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
        TTAdManagerHolder.get().requestPermissionIfNecessary((MainActivity) getCurrentActivity());
        //step3:创建TTAdNative对象,用于调用广告请求接口
        TTAdNative mTTAdNative = ttAdManager.createAdNative((MainActivity) getCurrentActivity());
        //step4:创建广告请求参数AdSlot,具体参数含义参考文档
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(codeId)
                .setSupportDeepLink(true)
                .setAdCount(2)
                .setImageAcceptedSize(1080, 1920)
                .setRewardName("金币") //奖励的名称
                .setRewardAmount(3)   //奖励的数量
                //必传参数，表来标识应用侧唯一用户；若非服务器回调模式或不需sdk透传
                //可设置为空字符串
                .setUserID("user123")
                .setOrientation(TTAdConstant.VERTICAL)  //设置期望视频播放的方向，为TTAdConstant.HORIZONTAL或TTAdConstant.VERTICAL
                .setMediaExtra("media_extra") //用户透传的信息，可不传
                .build();
        //step5:请求广告
        mTTAdNative.loadRewardVideoAd(adSlot, new TTAdNative.RewardVideoAdListener() {
            @Override
            public void onError(int code, String message) {
            //TToast.show(getCurrentActivity(), message + "message");
                WritableMap error = Arguments.createMap();
                error.putInt("code", code);
                error.putString("message", message);
                sendEvent(EVENT_AD_FAILED_TO_LOAD, error);
            }

            //视频广告加载后，视频资源缓存到本地的回调，在此回调后，播放本地视频，流畅不阻塞。
            @Override
            public void onRewardVideoCached() {
                // Log.e(TAG, "Callback --> onRewardVideoCached");
            }

            //视频广告的素材加载完毕，比如视频url等，在此回调后，可以播放在线视频，网络不好可能出现加载缓冲，影响体验。
            @Override
            public void onRewardVideoAdLoad(TTRewardVideoAd ad) {
                mttRewardVideoAd = ad;
                mttRewardVideoAd.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {
                    @Override
                    public void onAdShow() {
                        
                    }

                    @Override
                    public void onAdVideoBarClick() {
                        
                    }

                    @Override
                    public void onAdClose() {
                        
                    }

                    //视频播放完成回调
                    @Override
                    public void onVideoComplete() {
                        
                    }

                    @Override
                    public void onVideoError() {
                        
                    }

                    //视频播放完成后，奖励验证回调，rewardVerify：是否有效，rewardAmount：奖励梳理，rewardName：奖励名称
                    @Override
                    public void onRewardVerify(boolean rewardVerify, int rewardAmount, String rewardName) {
                        
                    }

                    @Override
                    public void onSkippedVideo() {
                        
                    }
                });

                mttRewardVideoAd.setDownloadListener(new TTAppDownloadListener() {
                    @Override
                    public void onIdle() {

                    }

                    @Override
                    public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {

                    }

                    @Override
                    public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {

                    }

                    @Override
                    public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {

                    }

                    @Override
                    public void onDownloadFinished(long totalBytes, String fileName, String appName) {

                    }

                    @Override
                    public void onInstalled(String fileName, String appName) {

                    }
                });

                getCurrentActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mttRewardVideoAd != null) {
                            mttRewardVideoAd.showRewardVideoAd(getCurrentActivity(), TTAdConstant.RitScenes.GAME_GIFT_BONUS, null);
                        }
                    }
                });
            }
        });
    }


    // // Draw信息流（类似抖音）
    // @ReactMethod 
    private void initTTDrawFeedAd(String codeId) {
        //step1:初始化sdk
        TTAdManager ttAdManager = TTAdManagerHolder.get();
        //step2:(可选，强烈建议在合适的时机调用):申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
        TTAdManagerHolder.get().requestPermissionIfNecessary((MainActivity) getCurrentActivity());
        //step3:创建TTAdNative对象,用于调用广告请求接口
        TTAdNative mTTAdNative = ttAdManager.createAdNative((MainActivity) getCurrentActivity());
        //step4:创建广告请求参数AdSlot,具体参数含义参考文档
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(codeId) //开发者申请的广告位
                .setSupportDeepLink(true)
                .setImageAcceptedSize(1080, 1920) //符合广告场景的广告尺寸
                .setAdCount(1) //请求广告数量为1到3条
                .build();
        //加载广告
        mTTAdNative.loadDrawFeedAd(adSlot, new TTAdNative.DrawFeedAdListener() {
            @Override
            public void onError(int code, String message) {
                WritableMap error = Arguments.createMap();
                error.putInt("code", code);
                error.putString("message", message);
                sendEvent(EVENT_AD_FAILED_TO_LOAD, error);
            }

            @Override
            public void onDrawFeedAdLoad(List<TTDrawFeedAd> ads) {
                if (ads == null || ads.isEmpty()) {
                    // TToast.show(DrawNativeVideoActivity.this, " ad is null!");
                    return;
                }

                for (TTDrawFeedAd ad : ads) {
                    ad.setActivityForDownloadApp(getCurrentActivity());
                    //是否允许点击暂停视频播放
                    ad.setCanInterruptVideoPlay(true);
                    //点击监听器必须在getAdView之前调
                    ad.setDrawVideoListener(new TTDrawFeedAd.DrawVideoListener() {
                        @Override
                        public void onClickRetry() {
                            
                        }

                        @Override
                        public void onClick() {
                            
                        }
                    });
                }

                //获取广告视频播放的view并放入广告容器中
                // ads.get(0).getAdView()

                getCurrentActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mSplashDialog = new Dialog(getCurrentActivity());
                        mSplashDialog.setContentView(ads.get(0).getAdView());
                        mSplashDialog.setCancelable(false);
                        mSplashDialog.show();
                    }
                });

                

            }

        });
    }

}
